from flask import Blueprint

api_bp = Blueprint('cart', __name__)

from flask import Blueprint, jsonify, g, current_app, request
from models import Cart, Product, db
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc

api_bp = Blueprint('cart', __name__)


# 1.获取购物车列表
@api_bp.route('/carts', methods=['GET'])
def get_cart_items():
    try:
        user_id = g.current_user.get('id')
        if not user_id:
            return jsonify({"message": "用户未登录"}), 401

        # 分页参数处理（默认每页10条，支持页码和每页数量自定义）
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        page_size = min(max(page_size, 1), 100)  # 限制每页最大数量为100条

        # 查询总记录数
        total_items = Cart.query.filter_by(user_id=user_id).count()

        # 计算总页数
        total_pages = (total_items + page_size - 1) // page_size
        page = max(1, min(page, total_pages))  # 防止页码越界

        # 分页查询购物车记录（按更新时间倒序排列，保证最新操作在前面）
        cart_items = Cart.query.filter_by(user_id=user_id) \
            .order_by(desc(Cart.updated_at)) \
            .offset((page - 1) * page_size) \
            .limit(page_size) \
            .all()

        # 组装返回数据
        data = []
        for cart in cart_items:
            product = Product.query.get(cart.product_id)
            data.append({
                "id": cart.id,
                "product_id": cart.product_id,
                "product_name": product.name,
                "price": float(product.price),
                "quantity": cart.quantity,
                "image": product.image,
                "created_at": cart.created_at.strftime("%Y-%m-%d %H:%M:%S"),
                "updated_at": cart.updated_at.strftime("%Y-%m-%d %H:%M:%S")
            })

        return jsonify({
            "message": "获取购物车成功",
            "data": data,
            "pagination": {
                "current_page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "total_items": total_items
            }
        }), 200

    except Exception as e:
        current_app.logger.error(f"获取购物车失败: {str(e)}", exc_info=True)
        return jsonify({"message": "获取购物车失败"}), 500


# 2. 添加商品到购物车
@api_bp.route('/carts', methods=['POST'])
def add_to_cart():
    try:
        user_id = g.current_user.get('id')
        if not user_id:
            return jsonify({"message": "用户未登录"}), 401

        # 校验请求参数
        data = request.json
        required_fields = ["product_id", "quantity"]
        for field in required_fields:
            if field not in data:
                return jsonify({"message": f"缺少必要参数: {field}"}), 400

        product_id = data["product_id"]
        quantity = int(data["quantity"]) if data["quantity"] else 1

        # 校验商品是否存在
        product = Product.query.get(product_id)
        if not product:
            return jsonify({"message": "商品不存在"}), 404

        # 检查购物车中是否已存在该商品
        existing_cart = Cart.query.filter_by(
            user_id=user_id,
            product_id=product_id
        ).first()

        if existing_cart:
            # 更新数量
            existing_cart.quantity += quantity
            db.session.commit()
            return jsonify({"message": "商品数量更新成功"}), 200
        else:
            # 新增购物车记录
            new_cart = Cart(
                user_id=user_id,
                product_id=product_id,
                quantity=quantity
            )
            db.session.add(new_cart)
            db.session.commit()
            return jsonify({
                "message": "商品添加到购物车成功",
                "cart_id": new_cart.id
            }), 201

    except IntegrityError:
        db.session.rollback()
        current_app.logger.error("数据库操作冲突")
        return jsonify({"message": "添加商品失败"}), 500
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"添加购物车失败: {str(e)}", exc_info=True)
        return jsonify({"message": "添加商品失败"}), 500


# 3. 更新购物车商品数量
@api_bp.route('/carts/<int:cart_id>', methods=['PUT'])
def update_cart_quantity(cart_id):
    try:
        user_id = g.current_user.get('id')
        if not user_id:
            return jsonify({"message": "用户未登录"}), 401

        # 校验数量参数
        data = request.json
        quantity = data.get("quantity")
        if quantity is None or quantity < 1:
            return jsonify({"message": "数量必须为正整数"}), 400

        # 查询购物车记录
        cart = Cart.query.filter_by(
            id=cart_id,
            user_id=user_id
        ).first()

        if not cart:
            return jsonify({"message": "购物车记录不存在"}), 404

        # 更新数量
        cart.quantity = quantity
        db.session.commit()

        return jsonify({
            "message": "商品数量更新成功",
            "cart_id": cart.id,
            "new_quantity": quantity
        }), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新购物车数量失败: {str(e)}", exc_info=True)
        return jsonify({"message": "更新数量失败"}), 500


# 4. 删除购物车商品
@api_bp.route('/carts/<int:cart_id>', methods=['DELETE'])
def delete_cart_item(cart_id):
    try:
        user_id = g.current_user.get('id')
        if not user_id:
            return jsonify({"message": "用户未登录"}), 401

        # 查询并删除购物车记录
        cart = Cart.query.filter_by(
            id=cart_id,
            user_id=user_id
        ).first()

        if not cart:
            return jsonify({"message": "购物车记录不存在"}), 404

        db.session.delete(cart)
        db.session.commit()

        return jsonify({"message": "商品已从购物车删除"}), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除购物车失败: {str(e)}", exc_info=True)
        return jsonify({"message": "删除商品失败"}), 500